package com.peanut.baby.mvp.main.circle;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.MyViewPagerAdapter;
import com.peanut.baby.comm.SmallPagerAdapter;
import com.peanut.baby.model.Ad;
import com.peanut.baby.model.BBSMoment;
import com.peanut.baby.model.CircleTrends;
import com.peanut.baby.model.User;
import com.peanut.baby.mvp.bbs.BBSListAdapter;
import com.peanut.baby.mvp.bbs.detail.BBSMomentDetailActivity;
import com.peanut.baby.mvp.bbs.list.BBSListActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.main.BaseHomeFragment;
import com.peanut.baby.mvp.main.MainActivity;
import com.peanut.baby.mvp.profile.ProfileActivity;
import com.peanut.baby.mvp.search.SearchActivity;
import com.peanut.baby.mvp.trend.detail.TrendDetailActivity;
import com.peanut.baby.mvp.trend.list.TrendListActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.widget.AutoSwitchViewPager;
import com.peanut.baby.widget.UnScrollGridView;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.FloatMenuMgr;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by anonymouslystudio on 2017/7/11.
 */

public class CircleFragment extends BaseHomeFragment implements CircleFragmentContract.View,
        FamousUserGridAdapter.CircleFamousListener,
        View.OnClickListener, SwipeRefreshLayout.OnRefreshListener,
        ViewPager.OnPageChangeListener {
    private static final String TAG = CircleFragment.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;

    Unbinder unbinder;
    @BindView(R.id.circle_self)
    LinearLayout circleSelf;
    @BindView(R.id.circle_hot)
    LinearLayout circleHot;
    @BindView(R.id.circle_grid)
    UnScrollGridView circleGrid;
    @BindView(R.id.circle_self_bar)
    RelativeLayout circleSelfBar;
    @BindView(R.id.famous_more)
    TextView famousMore;
    @BindView(R.id.self_more)
    TextView selfMore;
    @BindView(R.id.hot_more)
    TextView hotMore;
    @BindView(R.id.small_pager)
    AutoSwitchViewPager smallPager;
    @BindView(R.id.search_edit)
    TextView SearchEdit;
    @BindView(R.id.circle_talent_bar)
    RelativeLayout circleTalentBar;
    @BindView(R.id.circle_hot_bar)
    RelativeLayout circleHotBar;
    @BindView(R.id.swiper)
    SwipeRefreshLayout swiper;
    @BindView(R.id.banner_viewpager)
    ViewPager bannerViewpager;
    @BindView(R.id.banner_radiogroup)
    RadioGroup bannerRadiogroup;
    @BindView(R.id.banner_frame)
    FrameLayout bannerFrame;
    @BindView(R.id.circie_auto_viewpager)
    AutoSwitchViewPager trendViewPager;
    @BindView(R.id.trend1_area)
    View trend1Area;
    @BindView(R.id.trend2_area)
    View trend2Area;
    @BindView(R.id.circie_auto_viewpager_self)
    AutoSwitchViewPager trendViewPagerSelf;

    protected List<View> trendViewsSelf;
    protected CircleTrendViewPagerAdapter trendAdapterSelf;

    protected SmallPagerAdapter smallPagerAdapter;
    protected MyViewPagerAdapter mAdAdapter;                      //banner适配器
    protected List<View> mAdViews;
    protected List<View> trendViews;
    protected CircleTrendViewPagerAdapter trendAdapter;
    @BindView(R.id.menu_frame)
    FrameLayout menuFrame;
    private Runnable scrollRunnable;
    private boolean resumed = false;
    private Handler handler = new Handler();


    private LayoutInflater inflater;

    private CircleFragmentPresenter presenter;


    private int famousPageSize = 8;

    private int momentSize = 5;

    private FamousUserGridAdapter adapter;
    FloatMenuMgr menuMgr;

    public static CircleFragment newInstance() {
        return new CircleFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_circle, null);

        unbinder = ButterKnife.bind(this, rootView);
        initViews();
        return rootView;
    }

    private void initViews() {
        title.setTitleBackVisibility(false);
        title.setTitle("圈子");

        fixBannerSize();

        swiper.setOnRefreshListener(this);
        selfMore.setOnClickListener(this);
        famousMore.setOnClickListener(this);
        hotMore.setOnClickListener(this);
        SearchEdit.setOnClickListener(this);


    }



    @Override
    public void onResume() {
        super.onResume();
        smallPager.startPlay(AppConfig.smallPagerDuration);
        resumed = true;
        handler.postDelayed(scrollRunnable, 3000);

    }

    @Override
    public void onPause() {
        super.onPause();
        smallPager.stopPlay();
        resumed = false;
        handler.removeCallbacks(scrollRunnable);
        closeFloatMenu();


    }


    /**
     *
     */
    private void fixBannerSize() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bannerFrame.getLayoutParams();
        params.height = InitManager.getInstance().getScreenWidth() * 3 / 5;
        bannerFrame.setLayoutParams(params);
    }

    private void bindFamous(List<User> famous) {
        if (famous == null || famous.isEmpty()) {
            famousMore.setVisibility(View.GONE);
            if (adapter == null || adapter.getCount() <= 0) {
                circleTalentBar.setVisibility(View.GONE);
            }
            return;
        }
        circleTalentBar.setVisibility(View.VISIBLE);

        adapter = new FamousUserGridAdapter(getActivity(), famous);
        adapter.setCircleFamousListener(this);
        circleGrid.setAdapter(adapter);

        if (famous != null && famous.size() >= famousPageSize) {
            famousMore.setVisibility(View.VISIBLE);
        } else {
            famousMore.setVisibility(View.GONE);
        }
    }

    private void bindSelfCircleMoments(List<BBSMoment> moments) {
        Log.d(TAG, "bindSelfCircleMoments: " + (moments == null ? "null" : "size: " + (moments.size())));
        circleSelf.removeAllViews();
        if (moments == null || moments.isEmpty()) {
            circleSelf.setVisibility(View.GONE);
            circleSelfBar.setVisibility(View.GONE);
            return;
        }
        circleSelf.setVisibility(View.VISIBLE);
        circleSelfBar.setVisibility(View.VISIBLE);
        BBSListAdapter adapter = new BBSListAdapter(getActivity(), moments);
        for (int i = 0; i < moments.size(); i++) {
            View view = adapter.getView(i, null, null);
            circleSelf.addView(view);
            if (i == moments.size() - 1) {
                view.findViewById(R.id.bbs_divider).setVisibility(View.GONE);
            }
        }

        if (moments != null && moments.size() >= momentSize) {
            selfMore.setVisibility(View.VISIBLE);
        } else {
            selfMore.setVisibility(View.GONE);
        }
    }

    private void bindHotCircleMoments(List<BBSMoment> moments) {
        Log.d(TAG, "bindHotCircleMoments: " + (moments == null ? "null" : "size: " + (moments.size())));
        circleHot.removeAllViews();

        if (moments == null || moments.isEmpty()) {
            circleHot.setVisibility(View.GONE);
            circleHotBar.setVisibility(View.GONE);
            return;
        }
        circleHot.setVisibility(View.VISIBLE);
        circleHotBar.setVisibility(View.VISIBLE);

        BBSListAdapter adapter = new BBSListAdapter(getActivity(), moments);
        for (int i = 0; i < moments.size(); i++) {
            View view = adapter.getView(i, null, null);
            circleHot.addView(view);
        }

        if (moments != null && moments.size() >= momentSize) {
            hotMore.setVisibility(View.VISIBLE);
        } else {
            hotMore.setVisibility(View.GONE);
        }
    }

    private void initFloatMenu(){
        menuMgr = new FloatMenuMgr();
        menuMgr.init(menuFrame, type -> {
            ((MainActivity) getActivity()).onFloatMenuClicked(type);
        });
    }

    public void closeFloatMenu(){
        menuMgr.closeMenu();
    }

    @Override
    public void initData() {
        SearchEdit.setHint(InitManager.getInstance().getOneSearchKeyword());
        initFloatMenu();
        if (presenter == null) {
            presenter = new CircleFragmentPresenter(this, getActivity());
        }

        scrollRunnable = new Runnable() {
            @Override
            public void run() {
                if (mAdAdapter != null && mAdAdapter.getCount() > 0) {
                    int currentIndex = bannerViewpager.getCurrentItem();
                    int pos = currentIndex + 1;
                    if (pos > mAdAdapter.getCount() - 1) {
                        pos = 0;
                    }

                    bannerViewpager.setCurrentItem(pos);
                }
                if (resumed) {
                    handler.postDelayed(scrollRunnable, 3000);
                }
            }
        };


        if (InitManager.getInstance().getUser() == null
                || StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
            circleSelfBar.setVisibility(View.GONE);
            circleSelf.setVisibility(View.GONE);
        } else {
            circleSelfBar.setVisibility(View.VISIBLE);
            circleSelf.setVisibility(View.VISIBLE);
            presenter.getCircleMoments(1, momentSize);
        }
        initSmallViewPager();
        presenter.getBanner();

        presenter.getFamousUserList();

        presenter.getAllMoments(1, momentSize);
        presenter.getTrends();

    }
    private void initSmallViewPager(){
        smallPagerAdapter = new SmallPagerAdapter(getActivity());
        smallPager.setAdapter(smallPagerAdapter);

    }

    @Override
    public void refreshFragmentData() {
        Log.d(TAG, "refreshFragmentData1");
        swiper.setRefreshing(true);
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onRequestFailed(String reason) {
        swiper.setRefreshing(false);
        dismissProgress();
        showToast(reason);
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetFamousList(List<User> users) {
        swiper.setRefreshing(false);
        bindFamous(users);
    }

    @Override
    public void onGetAllMoments(List<BBSMoment> moments) {
        swiper.setRefreshing(false);
        bindHotCircleMoments(moments);
    }

    @Override
    public void onGetCircleMoments(List<BBSMoment> moments) {
        swiper.setRefreshing(false);
        bindSelfCircleMoments(moments);
    }

    @Override
    public void onChangeFollowStatusSuccess(User result) {
        dismissProgress();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onBannerGet(boolean success, List<Ad> ads, String failReason) {
        initBanners(ads);
    }

    @Override
    public void onTrendGets(boolean success, CircleTrends circleTrends, String failReason) {
        if(success){
            initCircleTrend1(circleTrends.circleTrend);
            initCircleTrend2(circleTrends.circleTrend2);
        } else {
            trendViewPagerSelf.setVisibility(View.GONE);
            trend1Area.setVisibility(View.GONE);
            trendViewPager.setVisibility(View.GONE);
            trend2Area.setVisibility(View.GONE);
        }
    }

    private void initCircleTrend1(List<BBSMoment> trends){
        if(trends == null || trends.isEmpty()){
            trendViewPagerSelf.setVisibility(View.GONE);
            trend1Area.setVisibility(View.GONE);
            return;
        }
        trendViewPagerSelf.setVisibility(View.VISIBLE);
        trend1Area.setVisibility(View.VISIBLE);
        Log.d(TAG, "onTrendGets " + (trends == null ? "null" : "size " + trends.size()));
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (trendViewsSelf == null) {
                        trendViewsSelf = new ArrayList<View>();
                    }
                    trendViewsSelf.clear();

                    int size = trends.size();

                    for (int i = 0; i < size; i++) {
                        final BBSMoment trend = trends.get(i);
                        final View trendView = getActivity().getLayoutInflater().inflate(R.layout.layout_item_circle_trend, null);
                        final ImageView avatar = (ImageView) trendView.findViewById(R.id.trend_avatar);
                        final TextView content = (TextView) trendView.findViewById(R.id.trend_content);
                        final TextView detail = (TextView) trendView.findViewById(R.id.trend_view_detail);

                        ImageLoader.getInstance().loadImageView(getActivity(), trend.avatar, avatar);
                        content.setText(Html.fromHtml(StringUtil.getSimpleText(trend.content)));
                        trendView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                TrendDetailActivity.start(getActivity(),trend.id+"");
                            }
                        });
                        detail.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                TrendListActivity.start(getActivity(),TrendListActivity.TYPE_ALL_CIRCLE);
                            }
                        });

                        trendViewsSelf.add(trendView);
                    }

                    trendAdapterSelf = new CircleTrendViewPagerAdapter(trendViewsSelf);
                    trendViewPagerSelf.setAdapter(trendAdapterSelf);
                    trendViewPagerSelf.startPlay(3000);
                }
            });
        }
    }
    private void initCircleTrend2(List<BBSMoment> trends){
        if(trends == null || trends.isEmpty()){
            trendViewPager.setVisibility(View.GONE);
            trend2Area.setVisibility(View.GONE);
            return;
        }
        trendViewPager.setVisibility(View.VISIBLE);
        trend2Area.setVisibility(View.VISIBLE);
        Log.d(TAG, "onTrendGets " + (trends == null ? "null" : "size " + trends.size()));
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (trendViews == null) {
                        trendViews = new ArrayList<View>();
                    }
                    trendViews.clear();

                    int size = trends.size();

                    for (int i = 0; i < size; i++) {
                        final BBSMoment trend = trends.get(i);
                        final View trendView = getActivity().getLayoutInflater().inflate(R.layout.layout_item_circle_trend, null);
                        final ImageView avatar = (ImageView) trendView.findViewById(R.id.trend_avatar);
                        final TextView content = (TextView) trendView.findViewById(R.id.trend_content);
                        final TextView detail = (TextView) trendView.findViewById(R.id.trend_view_detail);

                        ImageLoader.getInstance().loadImageView(getActivity(), trend.avatar, avatar);
                        content.setText(Html.fromHtml(StringUtil.getSimpleText(trend.content)));
                        trendView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                TrendDetailActivity.start(getActivity(),trend.id+"");
                            }
                        });
                        detail.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                               TrendListActivity.start(getActivity(),TrendListActivity.TYPE_ALL_CIRCLE);
                            }
                        });

                        trendViews.add(trendView);
                    }

                    trendAdapter = new CircleTrendViewPagerAdapter(trendViews);
                    trendViewPager.setAdapter(trendAdapter);
                    trendViewPager.startPlay(3000);
                }
            });
        }
    }

    private void initBanners(final List<Ad> objs) {
        Log.d(TAG, "initBanners " + (objs == null ? "null" : "size " + objs.size()));
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (objs == null || objs.isEmpty()) {
                        bannerFrame.setVisibility(View.GONE);
                        return;
                    }
                    bannerFrame.setVisibility(View.VISIBLE);
                    if (mAdViews == null) {
                        mAdViews = new ArrayList<View>();
                    }
                    mAdViews.clear();
                    bannerRadiogroup.removeAllViews();
                    int size = objs.size();
                    int rightMargin = getActivity().getResources().getDimensionPixelSize(R.dimen.ad_radio_size);
                    for (int i = 0; i < size; i++) {
                        final Ad ad = objs.get(i);
                        final View adView = getActivity().getLayoutInflater().inflate(R.layout.layout_ad, null);
                        final ImageView img = (ImageView) adView.findViewById(R.id.ad_image);

                        ImageLoader.getInstance().loadImageView(getActivity(), ad.imgUrl, img);


                        mAdViews.add(adView);

                        adView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                WebViewActivity.start(getActivity(), ad.htmlUrl, ad.name,ad.imgUrl);
                            }
                        });

                        RadioButton radioButton = new RadioButton(getActivity());
                        radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
                        try {
                            radioButton.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.selector_ad_radiobutton));
                        } catch (Resources.NotFoundException e) {
                            e.printStackTrace();
                        }
                        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(rightMargin, rightMargin);
                        if (i != (size - 1)) {
                            params.rightMargin = rightMargin;
                        }
                        bannerRadiogroup.addView(radioButton, params);


                    }
                    ((RadioButton) bannerRadiogroup.getChildAt(0)).setChecked(true);
                    mAdAdapter = new MyViewPagerAdapter(mAdViews);
                    bannerViewpager.setAdapter(mAdAdapter);
                    bannerViewpager.setOnPageChangeListener(CircleFragment.this);

                }
            });
        }
    }

    @Override
    public void onFollowStatusChanges(User famous) {
        if (InitManager.getInstance().getUser() == null) {
            LoginActivity.startForResult(getActivity());
            adapter.notifyDataSetChanged();
            return;
        }
        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
            BindMobileActivity.startForResult(getActivity());
            adapter.notifyDataSetChanged();
            return;
        }
        showProgress("请稍候...", false);
        presenter.changeFollowStatus(famous);
    }

    @Override
    public void onAvatarClicked(User famous) {
        ProfileActivity.start(getActivity(), famous.userId + "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.famous_more:
                presenter.getFamousUserList();
                break;
            case R.id.hot_more:
                BBSListActivity.start(getActivity(), BBSListActivity.TYPE_HOT_CIRCLE);
                break;
            case R.id.search_edit:
                SearchActivity.start(getActivity(),SearchEdit.getHint().toString());
                break;
            case R.id.self_more:
                if (InitManager.getInstance().getUser() == null) {
                    LoginActivity.startForResult(getActivity());
                    return;
                }
                BBSListActivity.start(getActivity(), BBSListActivity.TYPE_SELF_CIRCLE);
                break;

        }
    }

    @Override
    public void onRefresh() {
        initData();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        ((RadioButton) bannerRadiogroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
